package com.dbflow5.models;

import com.dbflow5.TestDatabase;
import com.dbflow5.config.FlowManager;

import com.dbflow5.BaseUnitTest;
import com.dbflow5.query.SQLite;
import com.dbflow5.structure.Model;
import org.junit.Assert;
import org.junit.Test;

public class QueryModelTest extends BaseUnitTest {
    @Test
    public void testCanLoadAuthorBlogs() {
        FlowManager.database(TestDatabase.class, db -> {
            ForeignKeyModels.Author author = new ForeignKeyModels.Author(0, "Andrew", "Grosner");
            Model.save(ForeignKeyModels.Author.class, author, db);
            ForeignKeyModels.Blog blog = new ForeignKeyModels.Blog(0, "My First Blog", author);
            Model.save(ForeignKeyModels.Blog.class, blog, db);

            assert(Model.exists(ForeignKeyModels.Author.class, author, db));
            assert(Model.exists(ForeignKeyModels.Blog.class, blog, db));

            QueryModels.AuthorNameQuery result = SQLite.select(Blog_Table.name.withTable().as("blogName"), Author_Table.id.withTable().as("authorId"),
                    Blog_Table.id.withTable().as("blogId"))
                    .from(ForeignKeyModels.Blog.class)
                    .innerJoin(ForeignKeyModels.Author.class)
                    .on(Blog_Table.author_id.withTable().eq (Author_Table.id.withTable()))
                    .queryCustomSingle(QueryModels.AuthorNameQuery.class, db);

            Assert.assertEquals(blog.id, result.blogId);
            return null;
        });
    }
}
